<?php

	// get time
	$time = time();

	// check param size and names
	if (sizeof($_POST) != 5 || !array_key_exists('s_code', $_POST) || !array_key_exists('un', $_POST) || !array_key_exists('lat', $_POST) || !array_key_exists('lon', $_POST) || !array_key_exists('acc', $_POST)) 
	{
		echo "Usage";
		exit;
	}

	// if passed then define vars
	$s_code = $_POST['s_code'];
	$un = $_POST['un'];
	$lat = $_POST['lat'];
	$lon = $_POST['lon'];
	$acc = $_POST['acc'];

	// if passed then check if code and un match
	$mysqli = new mysqli('localhost', 'root', 'project3', 'server1');
	if ($mysqli->connect_errno)
	{
		echo "DB connection error!";
		exit;
	}
	$res = $mysqli->query("select * from ia where s_code like '$s_code' and un like '$un'");
	if ($res->num_rows != 1)
	{
		echo 2;
		$res->close();
		$mysqli->close();
		exit;
	}

	// if passed then check if request made inside 30 secs
	$ob = $res->fetch_object();
	$res->close();
	if (time - intval($ob->time) > 30)
	{
		echo 1;
		$mysqli->close();
		exit;
	}
	
	// if passed then get the id and secret key
	$res = $mysqli->query("select * from ia_cred");
	$ob = $res->fetch_object();
	$id = $ob->id;
	$key = $ob->secretkey;
	$res->close();

	// if passed then query the IAS 
	$url = "http://173.1.2.194/requestIA.php?";
	$url .= "id=" . $id ;
	$url .= "&key=" . $key;
	$url .= "&hun=" . sha1($un);
	$url .= "&lat=" . $lat;
	$url .= "&lon=" . $lon;
	$url .= "&acc=" . $acc;

	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);

	// echo page according to result
        $json = json_decode($result);
        if ($json->result == '0' || $json->result == '3')
        {
                $lat = $json->lat;
                $lon = $json->lon;
                $acc = $json->acc;
                $dvlat = $json->dvlat;
                $dvlon = $json->dvlon;
                $dvacc = $json->dvacc;
                $dist = intval($json->dist);
                $maxDist = $json->maxDist;
                if ($json->result == '0')
                {
                        echo "Implicit Authentication was successful!<br /><br />Implicit Authentication details:<br /><br />Log-in location:<ul><li>latitude = $lat</li><li>longitude = $lon</li><li>accuracy = $acc meters</li></ul>2FA device location:<ul><li>latitude = $dvlat</li><li>longitude = $dvlon</li><li>accuracy = $dvacc meters</li></ul><br />Maximum allowed distance = $maxDist meters<br />Calculated distance = $dist meters<br />&nbsp;<hr>";
                }
                else
                {
                        echo "Implicit Authentication was not successful!<br /><br />Implicit Authentication details:<br /><br />Log-in location:<ul><li>latitude = $lat</li><li>longitude = $lon</li><li>accuracy = $acc meters</li></ul>2FA device location:<ul><li>latitude = $dvlat</li><li>longitude = $dvlon</li><li>accuracy = $dvacc meters</li></ul><br />Maximum allowed distance = $maxDist meters<br />Calculated distance = $dist meters<br />&nbsp;<hr>";
                        sendOtp($mysqli, $un);
                        $mysqli->close();
                        exit;
                }
        }
        else
        {
                // if result is not a json object
		sendOtp($mysqli, $un);
		echo "<br /><br />Implicit Authentication failed due to error code: " . "'$result'";
		$mysqli->close();
		exit;
	}

	$s = <<<EOT
	<!doctype html>
	<html>
		<head>
			<title>Server1 - Security Settings</title>
			<meta charset="utf-8">
	
			<script>
			function savesettings()
			{   
				var is2fa = (document.getElementById('2fa').checked ? true : false);
				var otptype = (document.getElementById('otppref-e').checked ? 'e' : 'p' );
				var isia = (document.getElementById('ia').checked ? true : false);
				xmlhttp = new XMLHttpRequest();
				xmlhttp.open("POST","savesettings.php");
				xmlhttp.onreadystatechange = function()
				{   
					if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
					{   
						if (xmlhttp.responseText == "0")
						{
							alert("Your settings have been saved");
							return;
						}
						if (xmlhttp.responseText == "4")
						{
							alert("Nothing changed!");
							return;
						}
						alert('Your setting have NOT been changed because: ' + xmlhttp.responseText);
					}   
				}   
				var fd = new FormData();
				fd.append('un', 
EOT;

				$s .= " '$un');";
				$s .= <<<EOT
				fd.append('is2fa', is2fa);
				fd.append('otptype', otptype);
				fd.append('isia', isia);
				xmlhttp.send(fd);
			}
			function restoreIA()
			{
				xhr = new XMLHttpRequest();
				xhr.open("POST", "restoreIA.php");
				xhr.onreadystatechange = function()
				{
					if (xhr.readyState == 4 && xhr.status == 200)
					{
						if (xhr.responseText == "0")
						{
							alert("Please check your email/phone for a message regarding restoring your account.");
							return;
						}
						alert("Error: " + xhr.responseText);
					}
				}
			

				var fd = new FormData();
				fd.append('un', 
EOT;

				$s .= " '$un');";
				$s .= <<<EOT
				xhr.send(fd);
			}   
			</script>

		</head>

		<body>
			<h1>Security Settings</h1>
			<table>
				<tr>
					<td width="150">Use 2FA</td>
					<td><input type="checkbox" name="cbs[]" id="2fa" value="2fa" 
EOT;

	$res = $mysqli->query("select * from users where un like '$un'");
	$ob = $res->fetch_object();

	if ($ob->is2fa == 'y')
	{
		$s .= "checked=\"yes\"";
	}

	$s .= <<<EOT
					/></td>
				</tr>
				<tr>
					<td>OTP method</td>
EOT;
	if ($ob->otppref == "e")
	{
		$s .= '<td><input type="radio" name="otppref" id="otppref-e" value="e" checked/>Email &nbsp;&nbsp;&nbsp;<input type="radio" name="otppref" id="otppref-p" value="p" />SMS</td>';
	}
	else
	{
		$s .= '<td><input type="radio" name="otppref" id="otppref-e" value="e" />Email &nbsp;&nbsp;&nbsp;<input type="radio" name="otppref" id="otppref-p" value="p" checked/>SMS</td>';
	}

	$s .= <<<EOT

				</tr>
				<tr>
					<td width="150">Use Impl. Auth.</td>
					<td><input type="checkbox" name="cbs[]" id="ia" value="ia" 
EOT;
	if ($ob->isia == 'y')
	{
		$s .= "checked=\"yes\"";
	}

	$s .= <<<EOT
						/></td>
					</tr>
					<tr>
						<td colspan="2" align="center" style="padding: 25px 0px" ><input type="submit" value="Save" onclick="savesettings()"/></td>
					</tr>
					<tr>
						<td colspan="2" align="center" style="padding: 25px 0px" ><input type="submit" value="Restore your IA account" onclick="restoreIA()"/></td>
					</tr>
				</table>
			</body>
		</html>
EOT;
	echo $s;
	$mysqli->close();


	/////////////////////////////////////////////////
	function sendOtp($mysqli, $un)
	{
		require_once "Mail.php";
		$from = "server1.2FA";
		$to = ""; // needs to be HERE!
		$subject = "Your server1 2FA code";
		$host = "ssl://smtp.gmail.com";
		$port = "465";
		$username = "cs249project3"; 
		$password = "project3";
		
		$s = <<<EOT
			<!doctype html>
			<html>
				<head>
					<title>Server1 - 2FA Authentication</title>
					<meta charset="utf-8">
				</head>
				<body>
					<p>An OTP code has been sent to your

EOT;
		
		$res = $mysqli->query("select * from users where un like '$un'");
		$ob = $res->fetch_object();
		$otptype = $ob->otppref;
		if ($otptype == 'e')
		{
			if ($ob->email == null)
			{
				echo "Error! Email required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->email;
			$res->close();
			
			$s .= " email address. <br />Please enter the code into the box below. </p>";
		}	
		else
		{
			if ($ob->phone == null)
			{
				echo "Error! Phone number required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->phone;
			$res->close();
			
			$s .= "phone number. <br />Please enter the code into the box below </p>";
		}	

		$otpcode = sha1(time());
		$sha1un = sha1($un);
		if (strlen($otpcode) == 40 && strlen($sha1un) == 40)
		{
			$res = $mysqli->query("select count(*) as count from 2fa where sha1un like '$sha1un'");
			$ob = $res->fetch_object();
			if ($ob->count == 0)
			{
				$res->close();
				$res = $mysqli->query("insert into 2fa values ('$sha1un', '$otpcode')");
			}
			else
			{
				$res->close();
				$res = $mysqli->query("update 2fa set code = '$otpcode' where sha1un like '$sha1un'");
			}
		}
		else
		{
			$res->close();
			echo "Error: SHA-1 size is not 40 chars!";
			exit();
		}

		$body = "Your OTP code is: $otpcode";
		$headers = array ('From' => $from,
		'To' => $to,
		'Subject' => $subject);
		$smtp = Mail::factory('smtp',
		array ('host' => $host,
		  'port' => $port,
		  'auth' => true,
		  'username' => $username,
		  'password' => $password));
		$mail = $smtp->send($to, $headers, $body);

		if (PEAR::isError($mail)) 
		{
			echo("Error: cannot send mail!");
			$mysqli->close();
			exit();
		} 
		else 
		{
			$s .= 		'<form name="2FA" method="post" action="2FA.php">
							<input type="hidden" name="sha1un" value="' . $sha1un . '" />
							<input type="hidden" name="un" value="' . $un . '" />
							<input type="text" name="otpcode" size="50" />
							&nbsp;&nbsp;&nbsp;<input type="submit" value="Go">
						</form>
					</body>
				</html>';
			echo $s;
		}
	}	
?>
